<template>
  <el-container>
    <!-- 侧边栏 -->
    <el-aside width="200px" style="height: 98vh;">
      <NavMenu/>
    </el-aside>

    <!-- 右侧内容 -->
    <el-container>
      <el-header>
        <div class="header-left">
          <el-avatar :size="40" :src="user.avatar" style="vertical-align: middle; margin-right: 10px;"/>
          <span>
            <el-text type="primary" class="username">
              {{ user.username }}
            </el-text>
          </span>
        </div>
        <div class="header-center">
          <span class="system-title">反诈平台管理系统</span>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click" @command="handleCommand">
            <span class="user-link">
              <el-icon><setting/></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <el-text type="primary" @click="handleCommand('view')">查看信息</el-text>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-text type="warning" @click="handleCommand('edit')">修改信息</el-text>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-text type="danger" @click="handleCommand('logout')">退出登录</el-text>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-main>
        <router-view/>
      </el-main>
    </el-container>
  </el-container>

  <!-- 查看用户信息弹窗 -->
  <el-dialog
    title="用户信息"
    v-model="viewDialogVisible"
    width="30%"
    class="user-info-dialog"
    :close-on-click-modal="false"
  >
    <el-descriptions :column="1" border>
      <el-descriptions-item label="用户ID">{{ user.id }}</el-descriptions-item>
      <el-descriptions-item label="用户名">{{ user.username }}</el-descriptions-item>
      <el-descriptions-item label="真实姓名">{{ user.userRealName }}</el-descriptions-item>
      <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
      <el-descriptions-item label="电话">{{ user.phone }}</el-descriptions-item>
      <el-descriptions-item label="性别">{{ user.gender === 1 ? '男' : '女' }}</el-descriptions-item>
      <el-descriptions-item label="用户类型">{{ formatUserType(user.type) }}</el-descriptions-item>
      <el-descriptions-item label="注册时间">{{ user.createTime }}</el-descriptions-item>
      <el-descriptions-item label="最后更新">{{ user.updateTime }}</el-descriptions-item>
    </el-descriptions>
  </el-dialog>

  <!-- 修改用户信息弹窗 -->
  <el-dialog
    title="修改信息"
    v-model="editDialogVisible"
    @close="resetForm"
    width="40%"
    class="edit-info-dialog"
    :close-on-click-modal="false"
  >
    <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :action="BaseURL + '/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar"/>
          <el-icon v-else class="avatar-uploader-icon"><plus/></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="真实姓名" prop="userRealName">
        <el-input v-model="editForm.userRealName" placeholder="请输入真实姓名"/>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="editForm.email" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input v-model="editForm.phone" placeholder="请输入电话"/>
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="editForm.gender" placeholder="请选择性别">
          <el-option :value="1" label="男"/>
          <el-option :value="2" label="女"/>
        </el-select>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="editForm.password" type="password" placeholder="不修改请留空"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="editForm.confirmPassword" type="password" placeholder="不修改请留空"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="editDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="saveUserInfo">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, computed, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {getUser, setUser, clearAuth} from '@/utils/auth';
import NavMenu from "@/components/NavMenu.vue";
import {Plus, Setting} from "@element-plus/icons-vue";
import {userUpdateOne} from '@/api/user.js';
import {BaseURL} from "@/utils/http.js";

const router = useRouter();

// 用户信息
const user = computed(() => getUser());

// 控制弹窗
const viewDialogVisible = ref(false);
const editDialogVisible = ref(false);

// 修改表单
const editForm = reactive({
  id: 0,
  userRealName: '',
  email: '',
  phone: '',
  gender: 1,
  avatar: '',
  password: '',
  confirmPassword: '',
});
const editFormRef = ref(null);

// 验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback();
  } else {
    if (editForm.confirmPassword !== '') {
      editFormRef.value?.validateField('confirmPassword');
    }
    callback();
  }
};

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback();
  } else if (value !== editForm.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

const rules = {
  userRealName: [
    {required: true, message: '请输入真实姓名', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {type: 'email', message: '邮箱格式错误', trigger: 'blur'},
  ],
  phone: [
    {required: true, message: '请输入电话', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '电话格式错误', trigger: 'blur'},
  ],
  password: [
    { validator: validatePass, trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validatePass2, trigger: 'blur' }
  ],
};

// 用户类型格式化
const formatUserType = (type) => {
  switch (type) {
    case 0:
      return '管理员';
    case 1:
      return '医生';
    case 2:
      return '普通用户';
    default:
      return '未知用户';
  }
};

// 头像上传相关方法
const handleAvatarSuccess = (response) => {
  editForm.avatar = response.data;
  console.log(editForm.avatar)
};

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
  const isLt2M = file.size / 1024 / 1024 < 10;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG/GIF 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 10MB!');
  }
  return isJPG && isLt2M;
};

// 下拉菜单操作
const handleCommand = (command) => {
  if (command === 'view') {
    viewDialogVisible.value = true;
  } else if (command === 'edit') {
    editDialogVisible.value = true;
    // 初始化编辑表单
    Object.assign(editForm, {
      id: user.value.id,
      userRealName: user.value.userRealName,
      email: user.value.email,
      phone: user.value.phone,
      gender: user.value.gender,
      avatar: user.value.avatar,
      password: '',
      confirmPassword: '',
    });
  } else if (command === 'logout') {
    clearAuth();
    router.push('/login');
  }
};

// 保存修改后的信息
const saveUserInfo = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const updateData = {...editForm};
        // 如果密码为空，则不更新密码
        if (!updateData.password) {
          delete updateData.password;
          delete updateData.confirmPassword;
        } else {
          delete updateData.confirmPassword;
        }

        await userUpdateOne(updateData);
        // 更新本地存储的用户信息
        const updatedUser = {...user.value, ...updateData};
        setUser(updatedUser);
        ElMessage.success('信息更新成功');
        editDialogVisible.value = false;
      } catch (error) {
        ElMessage.error('信息更新失败');
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  editFormRef.value?.resetFields();
};

onMounted(() => {
  // 初始化用户信息（如果未登录则跳转）
  if (!user.value.username) {
    router.push('/login');
  }
});
</script>

<style>
.el-header {
  background-color: #fff;
  color: #333;
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
}

.header-left {
  display: flex;
  align-items: center;
  width: 200px;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header-right {
  width: 200px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.system-title {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
}

.user-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 20px;
  color: #606266;
}

.user-link:hover {
  color: #409EFF;
}

.username {
  font-size: 14px;
}

/* 弹窗样式 */
.user-info-dialog .el-dialog__header,
.edit-info-dialog .el-dialog__header {
  margin-right: 0;
  border-bottom: 1px solid #dcdfe6;
  padding: 20px;
}

.user-info-dialog .el-dialog__body,
.edit-info-dialog .el-dialog__body {
  padding: 30px 20px;
}

.user-info-dialog .el-dialog__footer,
.edit-info-dialog .el-dialog__footer {
  border-top: 1px solid #dcdfe6;
  padding: 20px;
}

/* 头像上传样式 */
.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

/* 描述列表样式 */
.el-descriptions {
  padding: 20px;
}

.el-descriptions__label {
  width: 120px;
  color: #606266;
}

.el-descriptions__content {
  color: #303133;
}

/* 表单样式 */
.el-form-item__label {
  font-weight: 500;
}

.el-input__wrapper {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.el-input__wrapper:hover {
  box-shadow: 0 0 0 1px #409EFF inset;
}

.el-input__wrapper.is-focus {
  box-shadow: 0 0 0 1px #409EFF inset;
}
</style>
